var express = require('express');
var router = express.Router();
const db = require('../db')
/* GET home page. */
router.get('/', function (req, res, next) {
  var sql = 'select id,name,price,image,add_time from products order by add_time desc limit 0,4';
  db.conn.query(sql, function (err, result) {
    if (err) {
      console.log(err)
    } else {
      console.log(result);
      res.render('index.ejs', { products: result });
    }
  })
  res.render('index', { title: 'Express' });
});

// router.get('/products', function (req, res, next) {
//   var reqAttributes = {
//     'originalUrl': req.originalUrl,
//     'hostname': req.hostname,
//     'ip': req.ip,
//     'method': req.method,
//     'path': req.path,
//     'protocol': req.protocol,
//     'query': req.query,
//     'secure': req.secure,
//     'xhr': req.xhr
//   }
//   res.send(reqAttributes)
// })

router.get('/product', function (req, res, next) {
  var cat_id = req
  if (cat_id) {
    var sql = "select * from product where cat_id=? order by id desc"
    var sqlParams = [cat_id]
  } else {
    var sqlStr = "select* from product order by id desc"
    var sqlParams = []
  }
  db.conn.query(sqlStr, sqlParams, function (err, result) {
    if (err) {
      console.log(err)
    } else {
      res.send(result)
    }
    res.render('productList.ejs', { products: result })
  })
})

router.get('/detail/:id', function (req, res, next) {
  var id = req.params.id
  var sqlStr = "select * from product where id=?"
  var sqlParams = [id]
  db.conn.query(sqlStr, sqlParams, function (err, result) {
    if (err) {
      console.log(err)
    } else {
      res.send(result)
    }
    res.render('detail.ejs', { OneProduct: result })
  })
})

router.get('/page/:pid', function (req, res, next) {
  var pid = req.params.pid;
  var sqlstr = "SELECT id, page_name, content FROM page WHERE id=?";
  var sqlParam = [pid];

  db.com.query(sqlstr, sqlParam, function (err, result) {
    if (err) {
      console.log(err);
      return;
    }
    console.log(result); // [{}] 数组，只有一个元素
    res.render('page.ejs', { pageContent: result });
  });
});


module.exports = router;
